<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" th:replace="fragments/layout :: layout(~{::title}, ~{::section})">

<head>
    <title>图书分类列表 - 图书馆管理系统</title>
</head>

<body>
    <section>
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>图书分类列表</h2>
            <button class="btn btn-primary" data-toggle="modal" data-target="#addCategoryModal">
                <i class="fas fa-plus"></i> 添加分类
            </button>
        </div>

        <!-- 搜索表单 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">搜索条件</h5>
            </div>
            <div class="card-body">
                <form id="searchForm">
                    <div class="form-row">
                        <div class="form-group col-md-4">
                            <label for="name">分类名称</label>
                            <input type="text" class="form-control" id="name" name="name">
                        </div>
                        <div class="form-group col-md-8 d-flex align-items-end">
                            <button type="button" id="searchBtn" class="btn btn-primary mr-2">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button type="button" id="resetBtn" class="btn btn-secondary">
                                <i class="fas fa-redo"></i> 重置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <!-- 调试信息 -->
        <div class="alert alert-info" id="debugInfo" style="display:none;">
            <pre id="debugContent"></pre>
        </div>

        <!-- 分类列表 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">分类列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>名称</th>
                                <th>描述</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="categoryList">
                            <!-- 分类数据将通过AJAX加载 -->
                        </tbody>
                    </table>
                </div>

                <!-- 分页 -->
                <nav aria-label="Page navigation" class="mt-4">
                    <ul class="pagination justify-content-center" id="pagination">
                        <!-- 分页将通过AJAX加载 -->
                    </ul>
                </nav>
            </div>
        </div>

        <!-- 添加分类模态框 -->
        <div class="modal fade" id="addCategoryModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">添加分类</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="addCategoryForm">
                            <div class="form-group">
                                <label for="addName">分类名称</label>
                                <input type="text" class="form-control" id="addName" name="name" required>
                            </div>
                            <div class="form-group">
                                <label for="addDescription">分类描述</label>
                                <textarea class="form-control" id="addDescription" name="description"
                                    rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="saveAddBtn">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 编辑分类模态框 -->
        <div class="modal fade" id="editCategoryModal" tabindex="-1" role="dialog" aria-hidden="true">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">编辑分类</h5>
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <form id="editCategoryForm">
                            <input type="hidden" id="editId" name="id">
                            <div class="form-group">
                                <label for="editName">分类名称</label>
                                <input type="text" class="form-control" id="editName" name="name" required>
                            </div>
                            <div class="form-group">
                                <label for="editDescription">分类描述</label>
                                <textarea class="form-control" id="editDescription" name="description"
                                    rows="3"></textarea>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="saveEditBtn">保存</button>
                    </div>
                </div>
            </div>
        </div>

        <script th:inline="javascript">
            $(document).ready(function () {
                // 定义全局变量
                let currentPage = 1;
                let pageSize = 10;

                // 页面加载时获取数据
                loadData();

                // 搜索按钮点击事件
                $('#searchBtn').click(function () {
                    currentPage = 1;
                    loadData();
                });

                // 重置按钮点击事件
                $('#resetBtn').click(function () {
                    $('#searchForm')[0].reset();
                    currentPage = 1;
                    loadData();
                });

                // 保存添加按钮点击事件
                $('#saveAddBtn').click(function () {
                    const name = $('#addName').val();
                    const description = $('#addDescription').val();

                    if (!name) {
                        alert('请输入分类名称！');
                        return;
                    }

                    $.ajax({
                        url: '/category/api/add',
                        type: 'POST',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({
                            name: name,
                            description: description
                        }),
                        success: function (res) {
                            if (res.code === 200) {
                                alert('添加成功！');
                                $('#addCategoryModal').modal('hide');
                                $('#addCategoryForm')[0].reset();
                                loadData();
                            } else {
                                alert('添加失败：' + res.message);
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('AJAX错误:', status, error);
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                });

                // 保存编辑按钮点击事件
                $('#saveEditBtn').click(function () {
                    const id = $('#editId').val();
                    const name = $('#editName').val();
                    const description = $('#editDescription').val();

                    if (!name) {
                        alert('请输入分类名称！');
                        return;
                    }

                    $.ajax({
                        url: '/category/api/update',
                        type: 'PUT',
                        contentType: 'application/json; charset=utf-8',
                        data: JSON.stringify({
                            id: id,
                            name: name,
                            description: description
                        }),
                        success: function (res) {
                            if (res.code === 200) {
                                alert('更新成功！');
                                $('#editCategoryModal').modal('hide');
                                loadData();
                            } else {
                                alert('更新失败：' + res.message);
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('AJAX错误:', status, error);
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                });

                // 加载数据函数
                function loadData() {
                    // 获取表单数据
                    const formData = {
                        name: $('#name').val(),
                        pageNum: currentPage,
                        pageSize: pageSize
                    };

                    // 显示加载中提示
                    $('#categoryList').html('<tr><td colspan="5" class="text-center"><div class="spinner-border text-primary" role="status"><span class="sr-only">Loading...</span></div></td></tr>');

                    // 发送AJAX请求
                    $.ajax({
                        url: '/category/api/list',
                        type: 'GET',
                        data: formData,
                        dataType: 'json',
                        success: function (res) {
                            console.log('API响应:', res);

                            // 不显示调试信息
                            // $('#debugContent').text(JSON.stringify(res, null, 2));
                            // $('#debugInfo').show();

                            if (res && res.code === 200) {
                                renderTable(res.data);
                                renderPagination(res.data);
                            } else {
                                let errorMsg = res ? res.message : '未知错误';
                                $('#categoryList').html('<tr><td colspan="5" class="text-center text-danger">获取数据失败：' + errorMsg + '</td></tr>');
                                $('#pagination').html('');
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('AJAX错误:', status, error);
                            $('#categoryList').html('<tr><td colspan="5" class="text-center text-danger">服务器错误，请稍后再试！</td></tr>');
                            $('#pagination').html('');

                            // 只在出错时显示调试信息
                            $('#debugContent').text('错误状态: ' + status + '\n错误信息: ' + error + '\n响应文本: ' + xhr.responseText);
                            $('#debugInfo').show();
                        }
                    });
                }

                // 渲染表格数据
                function renderTable(data) {
                    if (!data || !data.list) {
                        $('#categoryList').html('<tr><td colspan="5" class="text-center">数据格式错误</td></tr>');
                        return;
                    }

                    const list = data.list;
                    let html = '';

                    if (list && list.length > 0) {
                        for (let i = 0; i < list.length; i++) {
                            const category = list[i];
                            html += `
                                <tr>
                                    <td>${category.id}</td>
                                    <td>${category.name}</td>
                                    <td>${category.description || '-'}</td>
                                    <td>${new Date(category.createTime).toLocaleString()}</td>
                                    <td>
                                        <div class="btn-group btn-group-sm">
                                            <button type="button" class="btn btn-primary" onclick="editCategory(${category.id}, '${category.name}', '${category.description || ''}')">
                                                <i class="fas fa-edit"></i> 编辑
                                            </button>
                                            <button type="button" class="btn btn-danger" onclick="deleteCategory(${category.id})">
                                                <i class="fas fa-trash"></i> 删除
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                            `;
                        }
                    } else {
                        html = '<tr><td colspan="5" class="text-center">暂无数据</td></tr>';
                    }

                    $('#categoryList').html(html);
                }

                // 渲染分页
                function renderPagination(data) {
                    if (!data || typeof data.total === 'undefined') {
                        $('#pagination').html('');
                        return;
                    }

                    const total = data.total;
                    const totalPages = Math.ceil(total / pageSize);
                    let html = '';

                    // 上一页
                    html += `
                        <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage - 1})">
                                <i class="fas fa-chevron-left"></i>
                            </a>
                        </li>
                    `;

                    // 页码
                    for (let i = 1; i <= totalPages; i++) {
                        html += `
                            <li class="page-item ${currentPage === i ? 'active' : ''}">
                                <a class="page-link" href="javascript:void(0);" onclick="changePage(${i})">${i}</a>
                            </li>
                        `;
                    }

                    // 下一页
                    html += `
                        <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                            <a class="page-link" href="javascript:void(0);" onclick="changePage(${currentPage + 1})">
                                <i class="fas fa-chevron-right"></i>
                            </a>
                        </li>
                    `;

                    $('#pagination').html(html);
                }

                // 将函数暴露到全局作用域
                window.loadData = loadData;
            });

            // 切换页码
            function changePage(page) {
                if (page < 1) page = 1;
                window.currentPage = page;
                window.loadData();
            }

            // 编辑分类
            function editCategory(id, name, description) {
                $('#editId').val(id);
                $('#editName').val(name);
                $('#editDescription').val(description);
                $('#editCategoryModal').modal('show');
            }

            // 删除分类
            function deleteCategory(id) {
                if (confirm('确定要删除这个分类吗？删除分类可能会影响相关图书的分类信息！')) {
                    $.ajax({
                        url: '/category/api/delete/' + id,
                        type: 'DELETE',
                        success: function (res) {
                            if (res.code === 200) {
                                alert('删除成功！');
                                window.loadData();
                            } else {
                                alert('删除失败：' + res.message);
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('AJAX错误:', status, error);
                            alert('服务器错误，请稍后再试！');
                        }
                    });
                }
            }
        </script>
    </section>
</body>

</html>